//
//  JXVideoRecordViewController.m
//  JXIntercomDemo
//
//  Created by Nansen on 2020/4/30.
//  Copyright © 2020 jingxi. All rights reserved.
//

#import "JXVideoRecordViewController.h"
#import <JXIntercomSDK/JXIntercomSDK.h>
#import "Masonry.h"

// 底部按钮到屏幕边缘的距离
static CGFloat const bottomM = 20.0f;
// 底部按钮的宽,高
static CGFloat const bottomBtnH = 24.0f;
// 滑动条和按钮的距离
static CGFloat const sliderLRM = 20.0f;


@interface JXVideoRecordViewController ()<JXVideoRecordPlayDelegate>

@property (nonatomic, strong) JXVideoRecordModel *videoRecord;

@property (nonatomic, strong) UIButton *playButton;

@property (nonatomic, strong) UIView *videoView;

@property (nonatomic, strong) UISlider *slider;
@property (nonatomic, strong) UILabel *timeLabel;
@property (nonatomic, copy) NSString *durationStr;
@property (nonatomic, strong) CATiledLayer *videoLayer;

@property (nonatomic, strong) UIImageView *coverImageView;

@property (nonatomic, strong) JXVideoRecordPlayTool *playTool;

@end

@implementation JXVideoRecordViewController

- (instancetype)initWithVideo:(JXVideoRecordModel *)videoRecordModel
{
    if (self = [super init]) {
        self.videoRecord = videoRecordModel;
        self.playTool = [[JXVideoRecordPlayTool alloc] initWithVideoRecord:videoRecordModel delegate:self];
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.view.backgroundColor = [UIColor whiteColor];
    self.title = @"录像";
    
    CGFloat sw = [UIScreen mainScreen].bounds.size.width;
    CGFloat vh = sw * 3.0 / 4.0;
    
    self.videoView = [[UIView alloc] init];
    self.videoView.backgroundColor = [UIColor blackColor];
    [self.view addSubview:self.videoView];
    [self.videoView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_equalTo(@0);
        make.centerY.mas_equalTo(@0);
        make.height.mas_equalTo(@(vh));
    }];
    
    self.videoLayer = [CATiledLayer layer];
    self.videoLayer.backgroundColor = [UIColor blackColor].CGColor;
    self.videoLayer.frame = CGRectMake(0, 0, sw, vh);
    [self.videoView.layer addSublayer:self.videoLayer];
    
    self.coverImageView = [[UIImageView alloc] init];
    self.coverImageView.image = [UIImage imageWithContentsOfFile:self.videoRecord.fullImagePath];
    [self.videoView addSubview:self.coverImageView];
    self.coverImageView.frame = self.videoLayer.bounds;
    
    
    self.playButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.playButton setImage:[UIImage imageNamed:@"start"] forState:UIControlStateNormal];
    [self.playButton setImage:[UIImage imageNamed:@"stop"] forState:UIControlStateSelected];
    self.playButton.backgroundColor = [UIColor redColor];
    [self.view addSubview:self.playButton];
    [self.playButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(bottomM);
        make.bottom.mas_equalTo(-bottomM-34);
        make.width.height.mas_equalTo(bottomBtnH);
    }];
    [self.playButton addTarget:self action:@selector(playClicked:) forControlEvents:UIControlEventTouchUpInside];
    
    UISlider *slider = [[UISlider alloc] init];
    [self.view addSubview:slider];
    [slider mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.playButton.mas_right).offset(sliderLRM);
        make.centerY.mas_equalTo(self.playButton.mas_centerY);
        make.right.mas_equalTo(-sliderLRM-bottomM-bottomBtnH);
    }];
    slider.minimumValue = 0;
    slider.maximumValue = 100;
    slider.value = 0;
    slider.continuous = YES;
    slider.minimumTrackTintColor = [UIColor blueColor];
    slider.maximumTrackTintColor = [UIColor redColor];
    [slider setThumbImage:[UIImage imageNamed:@"sp_cicle"] forState:UIControlStateNormal];
    [slider addTarget:self action:@selector(sliderValueChanged:forEvent:) forControlEvents:UIControlEventValueChanged];
    self.slider = slider;
    
    self.timeLabel = [[UILabel alloc] init];
    self.timeLabel.text = @"00:00";
    self.timeLabel.textColor = [UIColor blackColor];
    self.timeLabel.font = [UIFont systemFontOfSize:12];
    self.timeLabel.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:self.timeLabel];
    [self.timeLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(0);
        make.top.mas_equalTo(slider.mas_bottom).offset(10);
    }];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
 
    
    if (self.playButton.selected) {
        [self.playTool stop];
        self.playButton.selected = NO;
    }
}

- (void)playClicked:(UIButton *)button
{
    if (button.selected == NO) {
        // 播放
        JX_IntercomResultType result = [self.playTool playOnLayer:self.videoLayer];
        if (result == JX_IntercomResultType_Ok) {
            button.selected = YES;
        }
        
    }
    else {
        self.coverImageView.hidden = NO;
        [self.playTool stop];
        button.selected = NO;
    }
}


- (void)sliderValueChanged:(UISlider *)slider forEvent:(UIEvent *)event
{
    UITouch * touchEvent = [[event allTouches] anyObject];
    switch (touchEvent.phase) {
        case UITouchPhaseBegan:
        {
            slider.continuous = NO;
            break;
        }
        case UITouchPhaseEnded:
        {
            slider.continuous = YES;
            int progress = ceil(slider.value * 100 / slider.maximumValue);
            [self.playTool seekProgress:progress];
            break;
        }
        case UITouchPhaseCancelled:
        {
            slider.continuous = YES;
            break;
        }
        default:
            break;
    }
}



#pragma mark - ======== JXVideoRecordPlayDelegate ========
/// 获得此录像的总时长. play 之后会收到此回调.
/// @param duration 时长. 毫秒.
- (void)recordPlayDidGetVideoDuration:(NSInteger)duration
{
    self.coverImageView.hidden = YES;
    
    self.slider.maximumValue = duration;
    int seconds = ceil(duration / 1000.0);
    int s = seconds % 60;
    int m = seconds / 60;
    self.durationStr = [NSString stringWithFormat:@"%02d:%02d", m, s];
    self.timeLabel.text = [NSString stringWithFormat:@"00:00/%@", self.durationStr];
}

/// 录像的视频尺寸
/// @param size 视频尺寸
- (void)recordPlayDidChangeLayerSize:(CGSize)size
{
    CGFloat videoW = self.view.bounds.size.width;
    CGFloat videoH = videoW * 1.0 * size.height / size.width;
    [self.videoView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(videoH);
    }];
    self.videoLayer.frame = CGRectMake(0, 0, videoW, videoH);
    self.coverImageView.frame = CGRectMake(0, 0, videoW, videoH);
}

/// 播放进度
/// @param playTime 已播放的时长. 毫秒
/// @param totalTime 总时长. 毫秒
- (void)recordPlayDidPlayProgress:(NSInteger)playTime totalTime:(NSInteger)totalTime
{
    [self.slider setValue:playTime animated:YES];
    
    int seconds = ceil(playTime / 1000.0);
    int s = seconds % 60;
    int m = seconds / 60;
    self.timeLabel.text = [NSString stringWithFormat:@"%02d:%02d/%@", m, s, self.durationStr];
}

/// 播放完成
- (void)recordPlayDidPlayCompleted
{
    self.coverImageView.hidden = NO;
    
    self.playButton.selected = NO;
    [self.slider setValue:0 animated:YES];
    
    self.timeLabel.text = [NSString stringWithFormat:@"00:00/%@", self.durationStr];
}


@end
